<?php

namespace App\Admin\Controllers;

use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

use App\Models\Notice;
use App\Models\Squad;
use App\Models\Class_section_group;
use App\Models\Teaching_plan;
use App\Models\Study_jindu_record;
use Illuminate\Support\Facades\DB;

class Study_jindu_recordController  extends Controller {
    use ModelForm;

    public function index(Content $content) {
        $content->header('各种进度');
        $content->description('确认');
		$info = DB::table("notices as notice")
			->join("squads as squad",'squad.id','=','notice.squad_id')
			->join("class_section_groups as group",'group.id','=','squad.section')
			->where('notice.id','=',Request('notice_id'))
			->first(["group.name as section_name","notice.id as notice_id","squad.id as squad_id"]);
		$info = json_decode(json_encode($info),true);
		$plans = Teaching_plan::where([
			['title',"=",$info['section_name']],
			['parent_id',"=",'0'],
		])->groupBy("type")->get(['type','id'])->toArray();
		foreach($plans as $v){
			if($v['type'] == "reading"){
				$readonly = Teaching_plan::where('parent_id',$v['id'])->get(['title','id'])->toArray();
				$opts = [];
				foreach($readonly as $r){
					if($r['title'] == "A to Z"){
						$opts = Teaching_plan::where('parent_id',$r['id'])->get(['title','id'])->toArray();
					}
				}
				$content->row(view("admin.plans.reading_plan",[
					"Info" => $info,
					"PlanType" => $v,
					"ReadOnly" => $readonly,
					"Opts" => $opts
				]));
			}else{
				$content->row($this->mkForm($info,$v));
			}
			$types[] = $v['type'];
		}
		$content->row(view('admin.plans.study_jindu_confirm',['types'=>implode(",",$types)]));
        return $content;
    }
    protected function mkForm($info,$plan_type) {
        return Admin::form(Study_jindu_record::class,function (Form $form) use($info,$plan_type) {
            $form->setTitle(trans('admin.'.$plan_type['type']."_plan.header"));
			$readonly = Teaching_plan::where('parent_id',$plan_type['id'])->get(['title','id'])->toArray();
			$types = [];
			foreach($readonly as $k => $v){
				$type_field = $plan_type['type'].$k;
				$form->text($type_field,'教学线')->default($v['title'])->attribute('readonly', 'true');
				$book_opts = Teaching_plan::where('parent_id',$v['id'])->pluck('title','id')->toArray();
				$form->select($type_field.'_book','教材')->options($book_opts)
					->addElementLabelClass('must-input')
					->Myload($type_field.'_chapter', '/api/get_zhangjie')
					->rules('required','请选择教材');
				$form->select($type_field.'_chapter','章节')
					->options()
					->addElementLabelClass('must-input')
					->rules('required','请选择章节');
				$form->text($type_field.'_desc','班级目前所处章节学习得具体知识点(例如:How are you?问答句)');
				$form->divide();
				$types[] = $plan_type['type'];
			}
            //额外知识点
            $other_zhishi_id = Teaching_plan::where('parent_id','0')->where('title','额外知识点')->value('id');
            $section_plan_id = Teaching_plan::where('parent_id',$other_zhishi_id)->where('title',$info['section_name'])->value('id');

            $section_zhishi_plans = Teaching_plan::where('parent_id',$section_plan_id)->pluck('title','id')->toArray();
			if(!empty($section_zhishi_plans)){
				$form->checkbox('other_zhishi','额外知识点')->options($section_zhishi_plans)->stacked();
			}
            $form->hidden('squad_id')->value($info['squad_id']);
			$form->hidden('notice_id')->value($info['notice_id']);
            $form->hidden($plan_type['type']."_count")->value(sizeof($readonly));
            $form->disableReset();
			$form->disableSubmit();
            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
            });
        });
    }

    public function save(Request $request) {
        $params = $request->all();
		$types = explode(",",$params['types']);
		$json = [];
		$study_jindu = [];
		foreach($types as $t){
			$count = $params[$t."_count"];
			$data = [];
			switch ($t) {
				case 'reading':
					for($i=0;$i<$count;$i++){
						$arr = [
							'title' => $params[$t.$i],
						];
						if($params[$t.$i] == "A to Z"){
							$arr["atoz"] = $params[$t.$i."_atoz"];
							$arr["num"] = $params[$t.$i."_num"];
						}else{
							$arr["chapters"] = $params[$t.$i."_chapters"];
						}
						$data[] = $arr;
					}
					$data[] = [
						'percent' => $params['reading_percent']
					];
					break;
				case 'teaching':
					if($request->get('other_zhishi') == null){
						$other_zhishi_ids = [];
					}else{
						$other_zhishi_ids = $request->get('other_zhishi');
					}
					for($i=0;$i<$count;$i++){
						$chapter = Teaching_plan::where('id',$params[$t.$i."_chapter"])->value('title');
						$data[] = [
							'title' => $params[$t.$i],
							'book' => Teaching_plan::where('id',$params[$t.$i."_book"])->value('title'),
							'chapter' => $chapter,
							'desc' => $params[$t.$i."_desc"],
							'other_zhishi_id' => $request->get('other_zhishi'),
							'other_zhishi_title' =>
							 	Teaching_plan::whereIn('id',$other_zhishi_ids)->pluck('title')
						];
						$study_jindu[] = $chapter;
					}
					break;
				default:
					for($i=0;$i<$count;$i++){
						$data[] = [
							'title' => $params[$t.$i],
							'book' => Teaching_plan::where('id',$params[$t.$i."_book"])->value('title'),
							'chapter' => Teaching_plan::where('id',$params[$t.$i."_chapter"])->value('title'),
							'desc' => $params[$t.$i."_desc"],
						];
					}
					break;
			}
			$json[$t] = $data;
		}
		$insert = [
			'notice_id' => $params['notice_id'],
			'squad_id' => $params['squad_id'],
			'jindu_content' => json_encode($json)
		];
        $res = Study_jindu_record::create($insert);
        if ($res) {
            $notice = Notice::find($insert['notice_id']);
            //更新待办操作时间及状态
            $notice->operatetime = date('Y-m-d H:i:s');
            if ($notice->operatetime<$notice->endtime&&$notice->status == '1') {
                $notice->status = '2';
            }
            elseif($notice->operatetime>$notice->endtime&&$notice->status == '3') {
                $notice->status = '4';
            }
            $notice->save();
            //更新班级的教学进度
			DB::table("squads")->where("id",'=',$params['squad_id'])->update([
				'study_jindu' => implode("|",$study_jindu)
			]);
			return [
				'code'=>1,
				'msg'=>'教学进度确认成功！待办完成！本页将在 3秒 后跳转',
				'data'=>'/admin/my_todo_notices'
			];
        }else{
			return [
				'code'=>0,
				'msg'=>'教学进度确认失败！请重新确认！',
				'data'=>''
			];
        }
    }


	public function clearRecord(Request $r) {
		DB::beginTransaction();
		try {
			DB::table("study_jindu_records")
			->where("notice_id",'=',$r['notice_id'])
			->delete();
			DB::commit();
			return ['code'=>1,'msg'=>'删除成功','data'=>''];
		} catch (\Exception $e) {
			DB::rollback();
			return ['code'=>0,'msg'=>'failed:'.$e->getMessage(),'data'=>''];
		}
	}
}
